<template>
	<view class="pt20">
		<view class="pd30 bg-w">
			<!-- 头像 -->
			<view class="flex alcenter space">
				<view class="ft16 ftw600 text-default">
					头像
				</view>
				<view @click="changeAvatar" class="flex alcenter">
					<image class="member-face" :src="userInfo.avatar || '/static/images/default-avatar.png'"></image>
					<text class="iconfont iconbtn_arrowr text-info ml20"></text>
				</view>
			</view>
			<view class="line mt30 mb30"></view>

			<!-- 昵称 -->
			<view class="flex alcenter space">
				<view class="ft16 ftw600 text-default">
					昵称
				</view>
				<view @click="nickAlert = true" class="flex alcenter">
					<text class="ft16 text-info">{{ userInfo.name || userInfo.username || '未设置' }}</text>
					<text class="iconfont iconbtn_arrowr text-info ml20"></text>
				</view>
			</view>
			<view class="line mt30 mb30"></view>

			<!-- 性别 -->
			<view class="flex alcenter space">
				<view class="ft16 ftw600 text-default">
					性别
				</view>
				<view @click="nickAlert = true" class="flex alcenter">
					<text class="ft16 text-info">{{ genderText }}</text>
					<text class="iconfont iconbtn_arrowr text-info ml20"></text>
				</view>
			</view>
			<view class="line mt30 mb30"></view>

			<!-- 手机号 -->
			<view class="flex alcenter space">
				<view class="ft16 ftw600 text-default">
					手机号
				</view>
				<view class="flex alcenter">
					<text class="ft16 text-info">{{ userInfo.phone || '未绑定' }}</text>
					<text v-if="!userInfo.phone" @click="bindPhone" class="text-main ft14 ml20">去绑定</text>
					<text v-else class="iconfont iconbtn_arrowr text-info ml20"></text>
				</view>
			</view>
			<view class="line mt30 mb30"></view>

			<!-- 邮箱 -->
			<view class="flex alcenter space">
				<view class="ft16 ftw600 text-default">
					邮箱
				</view>
				<view @click="changeEmail" class="flex alcenter">
					<text class="ft16 text-info">{{ userInfo.email || '未设置' }}</text>
					<text class="iconfont iconbtn_arrowr text-info ml20"></text>
				</view>
			</view>
		</view>

		<!-- 退出登录 -->
		<view class="pd40 mt20 flex center ft16 ftw600 text-main bg-w" @click="logout">退出登录</view>

		<!-- 修改资料弹窗 -->
		<unio2o-modal @closed="nickAlert = false" title="修改资料" :show="nickAlert">
			<view class="pd30">
				<view class="pt20 text-center text-notice ft14">昵称</view>
				<view class="mt30 flex center">
					<input v-model="editForm.nickname" class="input-info text-center" type="text"
						placeholder-style="color:#cccccc;" placeholder="输入昵称" />
				</view>
				<view class="mt30 text-center text-notice ft14">性别</view>
				<view class="flex space alcenter mt40">
					<view v-for="(item, index) in sexFace" :key="index" class="col3 text-center">
						<image @click="selectGender(index)" :data-index="index" class="unio2o-sex-type"
							:src="editForm.gender == index ? item.iconOn : item.icon"></image>
					</view>
				</view>
				<view class="mt40">
					<button @click="saveProfile" :disabled="saving" class="btn-main ft18 ftw600 text-w">
						{{ saving ? '保存中...' : '确定保存' }}
					</button>
				</view>
			</view>
		</unio2o-modal>

		<!-- 绑定手机弹窗 -->
		<unio2o-modal @closed="phoneAlert = false" title="绑定手机号" :show="phoneAlert">
			<view class="pd30">
				<view class="mt30 flex center">
					<input v-model="phoneForm.phone" class="input-info text-center" type="number"
						placeholder-style="color:#cccccc;" placeholder="输入手机号" />
				</view>
				<view class="mt30 flex center">
					<input v-model="phoneForm.code" class="input-info text-center" type="number"
						placeholder-style="color:#cccccc;" placeholder="输入验证码" />
					<button @click="sendSmsCode" :disabled="sendingCode" class="btn-code ml20">
						{{ sendingCode ? `${countdown}s后重发` : '获取验证码' }}
					</button>
				</view>
				<view class="mt40">
					<button @click="bindPhoneSubmit" :disabled="binding" class="btn-main ft18 ftw600 text-w">
						{{ binding ? '绑定中...' : '确认绑定' }}
					</button>
				</view>
			</view>
		</unio2o-modal>

	</view>
</template>

<script>
import unio2oModal from '@/components/base/modal/modal.vue';
import { mapState, mapActions } from 'vuex';
import { chooseImageToBase64 } from '@/utils/common.js';

export default {
	components: {
		unio2oModal
	},
	data() {
		return {
			sexFace: [{
				icon: this.$config.staticUrl + 'icon_secrecy@2x.png',
				iconOn: this.$config.staticUrl + 'icon_secrecy_pre@2x.png'
			},
			{
				icon: this.$config.staticUrl + 'icon_men@2x.png',
				iconOn: this.$config.staticUrl + 'icon_men_pre@2x.png'
			},
			{
				icon: this.$config.staticUrl + 'icon_women@2x.png',
				iconOn: this.$config.staticUrl + 'icon_women_pre@2x.png'
			}
			],
			nickAlert: false,
			phoneAlert: false,
			saving: false,
			binding: false,
			sendingCode: false,
			countdown: 0,
			editForm: {
				nickname: '',
				gender: 0
			},
			phoneForm: {
				phone: '',
				code: ''
			}
		}
	},
	computed: {
		...mapState('user', ['userInfo']),

		genderText() {
			const genderMap = ['保密', '男', '女'];
			return genderMap[this.userInfo?.gender || 0];
		}
	},
	mounted() {
		this.initForm();
	},
	methods: {
		...mapActions('user', ['updateUserInfo', 'bindPhone', 'sendSmsCode', 'logout']),

		initForm() {
			if (this.userInfo) {
				this.editForm.nickname = this.userInfo.name || this.userInfo.username || '';
				this.editForm.gender = this.userInfo.gender || 0;
			}
		},

		// 修改头像
		async changeAvatar() {
			const _this = this;
			uni.showActionSheet({
				itemList: ['拍照', '从相册选择'],
				success: function (res) {
					const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];
					uni.chooseImage({
						count: 1,
						sourceType: sourceType,
						success: async function (res) {
							if (res.tempFilePaths.length > 0) {
								uni.showLoading({ title: '处理中...' });
								try {
									// 1. 压缩图片并转为base64
									const compressResult = await chooseImageToBase64(res);
									
									// 2. 优化文件名和文件类型生成
									// 获取原文件扩展名
									const originalFileName = res.tempFilePaths[0].split('/').pop();
									const fileExtension = originalFileName.lastIndexOf('.') > -1 ? originalFileName.split('.').pop().toLowerCase() : 'jpg';
									// 生成唯一文件名：avatar_用户ID_时间戳.扩展名
									const userId = _this.userInfo?.id || 'unknown';
									const timestamp = Date.now();
									const data = {
										base64: compressResult,
										fileName: 'avatar/' + userId + '_' + timestamp + '.' + fileExtension,
										fileType: fileExtension
									};
									
									// 3. 上传头像并更新用户信息
									const uploadResult = await _this.$api.user.uploadAvatar(data);
									
									if (uploadResult && uploadResult.data && uploadResult.data.url) {
										// 更新用户头像信息
										const updateResult = await _this.updateUserInfo({
											avatar: uploadResult.data.url
										});
										
										if (updateResult && updateResult.success) {
											uni.showToast({ 
												title: '头像更新成功', 
												icon: 'success' 
											});
										} else {
											uni.showToast({ 
												title: updateResult?.error || '头像更新失败', 
												icon: 'none' 
											});
										}
									} else {
										throw new Error('头像上传失败，未返回图片URL');
									}
								} catch (error) {
									console.error('头像处理失败:', error);
									uni.showToast({ 
										title: '头像处理失败', 
										icon: 'none' 
									});
								} finally {
									uni.hideLoading();
								}
							}
						}
					})
				},
				fail: function (res) {
					console.log('选择图片取消:', res.errMsg);
				}
			});
		},

		// 选择性别
		selectGender(index) {
			this.editForm.gender = index;
		},

		// 保存资料
		async saveProfile() {
			if (!this.editForm.nickname.trim()) {
				uni.showToast({
					title: '请输入昵称',
					icon: 'none'
				});
				return;
			}

			this.saving = true;
			try {
				const updateData = {
					name: this.editForm.nickname,
					gender: this.editForm.gender
				};

				const result = await this.updateUserInfo(updateData);
				if (result.success) {
					uni.showToast({
						title: '资料更新成功',
						icon: 'success'
					});
					this.nickAlert = false;
				} else {
					uni.showToast({
						title: result.error || '更新失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.showToast({
					title: '更新失败',
					icon: 'none'
				});
			} finally {
				this.saving = false;
			}
		},

		// 绑定手机
		bindPhone() {
			this.phoneAlert = true;
			this.phoneForm.phone = '';
			this.phoneForm.code = '';
		},

		// 发送验证码
		async sendSmsCode() {
			if (!this.phoneForm.phone || !/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			this.sendingCode = true;
			this.countdown = 60;

			try {
				const result = await this.sendSmsCode({
					phone: this.phoneForm.phone,
					type: 'bind'
				});
				if (result.success) {
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					});

					// 开始倒计时
					const timer = setInterval(() => {
						this.countdown--;
						if (this.countdown <= 0) {
							this.sendingCode = false;
							clearInterval(timer);
						}
					}, 1000);
				} else {
					uni.showToast({
						title: result.error || '发送失败',
						icon: 'none'
					});
					this.sendingCode = false;
				}
			} catch (error) {
				uni.showToast({
					title: '发送失败',
					icon: 'none'
				});
				this.sendingCode = false;
			}
		},

		// 提交绑定手机
		async bindPhoneSubmit() {
			if (!this.phoneForm.phone || !/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			if (!this.phoneForm.code) {
				uni.showToast({
					title: '请输入验证码',
					icon: 'none'
				});
				return;
			}

			this.binding = true;
			try {
				const result = await this.bindPhone({
					phone: this.phoneForm.phone,
					code: this.phoneForm.code
				});

				if (result.success) {
					uni.showToast({
						title: '手机号绑定成功',
						icon: 'success'
					});
					this.phoneAlert = false;
					// 更新用户信息
					await this.updateUserInfo({
						phone: this.phoneForm.phone
					});
				} else {
					uni.showToast({
						title: result.error || '绑定失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.showToast({
					title: '绑定失败',
					icon: 'none'
				});
			} finally {
				this.binding = false;
			}
		},

		// 修改邮箱
		changeEmail() {
			uni.showModal({
				title: '修改邮箱',
				content: '此功能暂未开放',
				showCancel: false
			});
		},

		// 退出登录
		async logout() {
			uni.showModal({
				title: '提示',
				content: '确定要退出登录吗？',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '退出中...'
						});
						await this.logout();
						uni.hideLoading();
					}
				}
			});
		}
	}
}
</script>

<style>
.member-face {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
}

.input-info {
	width: 630rpx;
	height: 120rpx;
	background: rgba(255, 255, 255, 1);
	border-radius: 16rpx;
	border: 2rpx solid rgba(230, 230, 230, 1);
	padding: 0 30rpx;
	font-size: 32rpx;
}

.unio2o-sex-type {
	width: 116rpx;
	height: 116rpx;
	border-radius: 58rpx;
}

.btn-code {
	width: 200rpx;
	height: 80rpx;
	background: #007AFF;
	color: white;
	border-radius: 8rpx;
	font-size: 28rpx;
	line-height: 80rpx;
}

.btn-code:disabled {
	background: #CCCCCC;
	color: #999999;
}

.btn-main:disabled {
	background: #CCCCCC;
	opacity: 0.6;
}

.line {
	width: 100%;
	height: 2rpx;
	background: #F0F0F0;
}

.space {
	justify-content: space-between;
}

.alcenter {
	align-items: center;
}

.flex {
	display: flex;
}

.center {
	justify-content: center;
}
</style>